from functools import wraps
from flask import Flask,render_template,session,redirect,url_for,request,jsonify


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return func(*args, **kwargs)
    return wrapper



# def role_required(Role_id):
#     def decorator(func):
#         @wraps(func)
#         def wrapper(*args, **kwargs):
#             if 'username' not in session:
#                 return redirect(url_for('login'))
#             try:
#                 mysql = MysqlUtil()
#                 user_id = mysql.fetchone("SELECT USER_id FROM user WHERE Name = %s", (session['username'],))['USER_id']
#                 print(user_id)
#                 role = mysql.fetchone("SELECT Role_id FROM user_role WHERE USER_id = %s", (user_id,))
#                 if role and role['Role_id'] == Role_id:
#                     return func(*args, **kwargs)
#             except Exception as e:
#                 print('角色检查失败:', e)
#                 abort(500)
#         return wrapper
#     return decorator


# def role_required(Role_id):
#     def decorator(func):
#         @wraps(func)
#         def wrapper(*args, **kwargs):
#             if 'username' not in session:
#                 return redirect(url_for('login'))
#             try:
#                 mysql = MysqlUtil()
#                 user_id = mysql.fetchone("SELECT USER_id FROM user WHERE Name = %s", (session['username'],))['USER_id']
#                 role_permission = mysql.fetchalls("""
#                       SELECT p.Permission_id
#                             FROM role r
#                             LEFT JOIN user_role ur ON r.Role_id = ur.Role_id
#                             LEFT JOIN role_permission rp ON r.Role_id = rp.Role_id
#                             LEFT JOIN permission p ON rp.Permission_id = p.Permission_id
#                             WHERE ur.USER_id = %s AND r.Role_id = %s
#                 """, (user_id, Role_id, ))
#
#                 print(role_permission)
#                 if role_permission:
#                     return func(*args, **kwargs)
#                 else:
#                     abort(403)  # Forbidden access
#             except Exception as e:
#                 print('角色检查失败:', e)
#                 abort(500)
#         return wrapper
#     return decorator
